﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using ID3TagLib;
using System.Xml.Serialization;
using System.Runtime.InteropServices;
using System.Xml;
using System.Data;
using Microsoft.WindowsAPICodePack.Shell;

namespace Home.ArtDB
{
    /// <summary>
    /// 
    /// </summary>
    public class ArtAudioFile : ArtFile
    {
        /// <summary></summary>
        private ID3File _file;

        #region DURATION
        ///// <summary></summary>
        //[DllImport("winmm.dll")]
        //private static extern int mciSendString(string strCommand, StringBuilder strReturn, int iReturnLength, IntPtr hwndCallback);

        //[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
        //public static extern int GetShortPathName(
        //         [MarshalAs(UnmanagedType.LPTStr)]
        //           string path,
        //         [MarshalAs(UnmanagedType.LPTStr)]
        //           StringBuilder shortPath,
        //         int shortPathLength
        //         );

        /// <summary>
        /// Spielzeit in Millisekunden
        /// </summary>
        /// <returns></returns>
        private ulong GetDuration()
        {
            ulong length = 0;


            ShellFile so = ShellFile.FromFilePath(FileName);
            double nanoseconds;
            double.TryParse(so.Properties.System.Media.Duration.Value.ToString(),
            out nanoseconds);
            Console.WriteLine("NanaoSeconds: {0}", nanoseconds);
            if (nanoseconds > 0)
            {
                length = (ulong)(nanoseconds * 0.0001);
            }

            //StringBuilder filename = new StringBuilder(255);

            //GetShortPathName(FileName, filename, filename.Capacity);

            //if (File.Exists(FileName))
            //{
            //    var error = mciSendString("open \"" + filename + "\" type mpegvideo alias MediaFile", null, 0, IntPtr.Zero);
            //    if (error != 0)
            //    {
            //        // Let MCI deside which file type the song is
            //        error = mciSendString("open \"" + filename + "\" alias MediaFile", null, 0, IntPtr.Zero);
            //    }

            //    mciSendString("set MediaFile time format milliseconds", null, 0, IntPtr.Zero);
            //    mciSendString("set MediaFile seek exactly on", null, 0, IntPtr.Zero);
            //    StringBuilder str = new StringBuilder(128);
            //    mciSendString("status MediaFile length", str, 128, IntPtr.Zero);
            //    length = Convert.ToUInt64(str.ToString());
            //    mciSendString("close MediaFile", null, 0, IntPtr.Zero);
            //}
            return length;
        }

        #endregion duration

        /// <summary>
        /// 
        /// </summary>
        /// <param name="parentCollection"></param>
        /// <param name="filename"></param>
        public ArtAudioFile(ArtFileCollection parentCollection, string filename) : base(parentCollection, filename) { }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="parentCollection"></param>
        /// <param name="row"></param>
        public ArtAudioFile(ArtFileCollection parentCollection, DataRow row) : base(parentCollection, row) { }

        /// <summary>
        /// 
        /// </summary>
        public override void Save()
        {
            base.Save();

            _file.Save(FileName);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="filename"></param>
        /// <returns></returns>
        public override void Load(string filename)
        {
            base.Load(filename);

            /// <summary></summary>
            ID3v1Tag v1Tag;

            /// <summary></summary>
            ID3v2Tag v2Tag;

            _file = new ID3File(FileName);

            v1Tag = _file.ID3v1Tag;
            v2Tag = _file.ID3v2Tag;

            try
            {
                string title = v2Tag.Get(FrameFactory.TitleFrameId, (v1Tag != null) ? v1Tag.Title : "[unbenannt]");
                string composer = v2Tag.Get(FrameFactory.ComposerFrameId, "");
                string artist = v2Tag.Get(FrameFactory.LeadArtistFrameId, (v1Tag != null) ? v1Tag.Artist : "[unbekannt]");
                string album = v2Tag.Get(FrameFactory.AlbumFrameId, (v1Tag != null) ? v1Tag.Album : "[unbekannt]");
                string year = v2Tag.Get(FrameFactory.YearFrameId, (v1Tag != null) ? v1Tag.Year : "");
                string comment = v2Tag.Get(FrameFactory.CommentFrameId, (v1Tag != null) ? v1Tag.Comment : "");
                string genre = v2Tag.Get(FrameFactory.ContentTypeFrameId, (v1Tag != null) ? v1Tag.Genre.ToString() : "None");
                string trackS = v2Tag.Get(FrameFactory.TrackNumberFrameId, (v1Tag != null) ? v1Tag.TrackNumber : "0");
                string language = v2Tag.Get(FrameFactory.LanguageFrameId, "");
                ulong duration = GetDuration();

                //HomeID
                if (v2Tag.Frames[FrameFactory.InitialKeyFrameId] == null)
                {
                    v2Tag.Frames.Add(FrameFactory.GetFrame(FrameFactory.InitialKeyFrameId));
                }

                TextFrame textFrame = (TextFrame)v2Tag.Frames[FrameFactory.InitialKeyFrameId];
                if (!textFrame.Text.StartsWith("mp3db_"))
                {
                    textFrame.Text = "mp3db_" + Guid.NewGuid().ToString();

                    Save();
                }

                string homeid = textFrame.Text;

                //Replacement
                title = title.Replace("'", "");
                artist = artist.Replace("'", "");
                album = album.Replace("'", "");

                int track = 0;
                if (trackS.Trim().Length.Equals(0))
                {
                    track = 0;
                }
                else if (trackS.Contains("/"))
                {
                    track = trackS.Split('/')[0].ToInt();
                }
                else
                {
                    track = trackS.ToInt();
                }

                FileInfo fi = new FileInfo(filename);
                long size = fi.Length;

                Language = language;
                Genre = genre;
                Composer = composer;
                Album = album;
                Track = track;
                Title = title;
                Artist = artist;
                Size = size;
                Duration = duration;
                Comment = comment;
                FileName = filename;
                HomeID = homeid;

                Valid = true;
            }
            catch
            {
                Valid = false;
            }
        }

    }

}
